package com.xcw.jac.multithreadeddownloader.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author xcw
 * @date 2023/8/9 20:18
 * @description 下载工具类
 */
public class HttpUtils {

    /**
     * 获取文件大小
     * @param url
     * @return
     * @throws IOException
     */
    public static long getHttpFileContentLength(String url) throws IOException {

        HttpURLConnection httpURLConnection = null;
        int length;
        try {
            httpURLConnection = getHttpURLConnection(url);
            length = httpURLConnection.getContentLength();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return length;
    }

    /**
     * 切分下载的方法
     * @param url
     * @param startPos
     * @param endPos
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpURLConnection(String url, long startPos, long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载区间是：{}-{}", startPos, endPos);
        if (endPos != 0) {
            httpURLConnection.setRequestProperty("RANGE", "bytes="+startPos + "-" + endPos);
        } else {
            httpURLConnection.setRequestProperty("RANGE", "bytes="+startPos + "-");
        }
        return httpURLConnection;
    }

    /**
     * 获取链接的方法
     * @param url
     * @return
     * @throws IOException
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
        return httpURLConnection;
    }

    /**
     * 获取下载文件名称
     * @param url
     * @return
     */
    public static String getHttpFileName(String url) {
        int index = url.lastIndexOf("/");
        return url.substring(index + 1);
    }
}
